package com.sky.controller.user;

import com.sky.dto.HistoryPageDTO;
import com.sky.dto.OrdersCancelDTO;
import com.sky.dto.OrdersSubmitDTO;
import com.sky.exception.BaseException;
import com.sky.result.PageResult;
import com.sky.result.Result;
import com.sky.service.user.OrderService;
import com.sky.vo.OrderSubmitVO;
import com.sky.vo.OrderVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;

@RestController
@Api("订单接口")
@RequestMapping("/user/order")
public class UserOrderController {
    @Autowired
    private OrderService orderService;


    @GetMapping("/getEstimatedDeliveryTime")
    public Result getEstimatedDeliveryTime(Long shopId,String customerAddress){
        LocalDateTime estimatedDeliveryTime = orderService.getEstimatedDeliveryTime(shopId, customerAddress);
        return Result.success(estimatedDeliveryTime);
    }

    /**
     * 下订单
     */
    @PostMapping("/submit")
    @ApiOperation("下订单")
    public Result submit(@RequestBody OrdersSubmitDTO dto){

        OrderSubmitVO submitVO = orderService.submit(dto);
        return Result.success(submitVO);
    }


    /**
     * 分页查询历史订单
     */
    @GetMapping("/historyOrders")
    @ApiOperation("分页查询历史订单")
    public Result queryHistoryOrders(HistoryPageDTO dto){
        PageResult result =  orderService.queryHistoryOrders(dto);
        return Result.success(result);
    }

    /**
     * 查询可退款的订单
     */
    @GetMapping("/queryOrdersCheckStatus")
    @ApiOperation("查看可退款的订单")
    public Result queryEnableRefund(HistoryPageDTO dto){
        dto.setStatus(dto.getPayStatus());
        PageResult pageResult = orderService.queryHistoryOrders(dto);
        return Result.success(pageResult);
    }

    /**
     * 查看订单详情
     */
    @GetMapping("/orderDetail/{orderId}")
    @ApiOperation("查看订单详情")
    public Result orderDetail(@PathVariable Long orderId){
        OrderVO vo = orderService.queryOrderDetail(orderId);
        return Result.success(vo);
    }

    /**
     * 取消订单
     */
    @PostMapping("/cancel/{id}")
    @ApiOperation("取消订单")
    public Result cancelOrder(@PathVariable Long id){
        OrdersCancelDTO ordersCancelDTO = new OrdersCancelDTO();
        ordersCancelDTO.setId(id);
        try {
            orderService.cancelOrder(ordersCancelDTO);
        } catch (Exception e) {
            throw new BaseException("该状态下无法直接取消,请联系商家");
        }
        return Result.success();
    }

    /**
     * 再来一单
     */
    @PostMapping("/repetition/{id}")
    @ApiOperation("再来一单")
    public Result oneMoreOrder(@PathVariable Long id){
        orderService.oneMoreOrder(id);
        return Result.success();
    }
}
